<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" :label="$t('customer.index.keywords')">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="$t('customer.index.queryKeywords')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="status" :label="$t('order.payStatus')">
          <el-select
            v-model="queryParams.status"
            :no-data-text="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            :placeholder="$t('common.choose')"
            style="width: 300px"
            @change="handleQuery"
          >
            <el-option
              v-for="item in payStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">
            {{ $t("common.search") }}
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">{{ $t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="'order:add'"
          type="success"
          icon="plus"
          @click="handleRenewOpenDialog()"
        >
          {{ $t("order.renew") }}
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="list"
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column :label="t('customer.index.customerName')" prop="customerName" />
        <el-table-column :label="$t('solution.name')" prop="customerSolution">
          <template #default="scope">
            {{ solutionOptions.get(scope.row.solutionId) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('product.name')" prop="title" />
        <el-table-column :label="t('product.price')" align="center">
          <template #default="scope">
            {{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column :label="t('order.payMethod')">
          <template #default="scope">
            <el-text v-if="scope.row.payMethod === 'bank_transfer'" type="primary">
              {{ t("order.payMethodOptions.bankTransfer") }}
            </el-text>
            <el-text v-else-if="scope.row.payMethod === 'ecpay'" type="primary">
              {{ t("order.payMethodOptions.ecpay") }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column :label="$t('order.payStatus')" align="center">
          <template #default="scope">
            <el-text v-if="scope.row.status === 0" type="danger">
              {{ t("order.payStatusOptions.0") }}
            </el-text>
            <el-text v-if="scope.row.status === 1" type="success">
              {{ t("order.payStatusOptions.1") }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column :label="$t('order.openStatus')" prop="customerStartAt">
          <template #default="scope">
            <el-text v-if="scope.row.openStatus === 0" class="mx-1" type="warning">
              {{ $t("order.openStatusOptions.0") }}
            </el-text>
            <el-text v-if="scope.row.openStatus === 1" class="mx-1" type="success">
              {{ $t("order.openStatusOptions.1") }}
            </el-text>
            <el-text v-if="scope.row.openStatus === 2" class="mx-1" type="danger">
              {{ $t("order.openStatusOptions.2") }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.createdAt')" prop="createdAt" width="180">
          <template #default="scope">
            {{ dayjs(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.action')" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0 && scope.row.payMethod === 'ecpay'"
              v-hasPerm="'order:add'"
              type="primary"
              size="small"
              link
              icon="credit_card"
              @click="gotoPay(scope.row.id)"
            >
              {{ $t("order.gotoPay") }}
            </el-button>
            <el-button
              v-if="scope.row.status !== 0 && scope.row.paymentResponse != null"
              v-hasPerm="'order:add'"
              type="primary"
              size="small"
              link
              icon="eye"
              @click="showPayResult(scope.row.paymentResponse)"
            >
              {{ $t("payment.payResult") }}
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              v-hasPerm="'order:edit'"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleRenewEditOpenDialog(scope.row.id)"
            >
              {{ $t("common.edit") }}
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              v-hasPerm="'order:delete'"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="renew_dialog.visible"
      :title="renew_dialog.title"
      :width="dialogWidth"
      @close="handleRenewCloseDialog"
    >
      <el-form ref="reNewFormRef" :model="renewForm" :rules="renewRules">
        <el-form-item :label="$t('order.product_name')" prop="productId">
          <el-select
            v-model="renewForm.productId"
            :no-match-text="$t('order.choose_product')"
            :no-data-text="$t('order.choose_product')"
            :placeholder="$t('order.choose_product')"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.payMethod')" prop="payMethod">
          <el-radio-group v-model="renewForm.payMethod">
            <el-radio value="bank_transfer">
              {{ $t("order.payMethodOptions.bankTransfer") }}
            </el-radio>
            <el-radio value="ecpay">
              {{ $t("order.payMethodOptions.ecpay") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="showOrderStatus" :label="$t('order.payStatus')" prop="status">
          <el-radio-group v-model="renewForm.status">
            <el-radio :value="0">
              {{ $t("order.payStatusOptions.0") }}
            </el-radio>
            <el-radio :value="1">
              {{ $t("order.payStatusOptions.1") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="addOrder" type="primary" @click="handleRenewSubmit">
            {{ t("common.confirm") }}
          </el-button>
          <el-button v-if="updateOrder" type="primary" @click="handleRenewEditSubmit">
            {{ t("common.confirm") }}
          </el-button>
          <el-button @click="handleRenewCloseDialog">{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <form :action="paymentData.PaymentUrl" method="post" target="_blank">
      <input type="hidden" name="MerchantID" :value="paymentData.MerchantID" />
      <input type="hidden" name="MerchantTradeNo" :value="paymentData.MerchantTradeNo" />
      <input type="hidden" name="MerchantTradeDate" :value="paymentData.MerchantTradeDate" />
      <input type="hidden" name="PaymentType" :value="paymentData.PaymentType" />
      <input type="hidden" name="TotalAmount" :value="paymentData.TotalAmount" />
      <input type="hidden" name="TradeDesc" :value="paymentData.TradeDesc" />
      <input type="hidden" name="ItemName" :value="paymentData.ItemName" />
      <input type="hidden" name="ReturnURL" :value="paymentData.ReturnURL" />
      <input type="hidden" name="ChoosePayment" :value="paymentData.ChoosePayment" />
      <input type="hidden" name="CheckMacValue" :value="paymentData.CheckMacValue" />
      <input type="hidden" name="EncryptType" :value="paymentData.EncryptType" />
      <input type="hidden" name="ClientBackURL" :value="paymentData.ClientBackURL" />
      <input type="hidden" name="OrderResultURL" :value="paymentData.OrderResultURL" />
      <input id="gotoPay" type="submit" style="display: none" />
    </form>
    <el-dialog
      v-model="showOrderPaymentDialog"
      :center="true"
      align-center
      :close-on-click-modal="false"
    >
      <el-text style="text-align: center">{{ t("payment.pendingPayment") }}</el-text>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOrderPaymentDialog = false">{{ t("common.cancel") }}</el-button>
          <el-button type="primary" @click="showOrderPaymentDialog = false">
            {{ t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showOrderPaymentResultDialog"
      :center="true"
      align-center
      :close-on-click-modal="false"
    >
      <el-descriptions class="margin-top" :title="t('payment.payResult')" :column="1" border>
        <el-descriptions-item :label="t('payment.tradeNo')">
          {{ payResult.TradeNo }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              {{ t("payment.payAmount") }}
            </div>
          </template>
          {{ payResult.TradeAmt }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              {{ t("payment.payType") }}
            </div>
          </template>
          {{ payResult.PaymentType }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              {{ t("payment.tradeStatus") }}
            </div>
          </template>

          <el-tag size="small">{{ payResult.RtnMsg }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              {{ t("payment.payTime") }}
            </div>
          </template>
          {{ payResult.PaymentDate }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOrderPaymentResultDialog = false">
            {{ t("common.cancel") }}
          </el-button>
          <el-button type="primary" @click="showOrderPaymentResultDialog = false">
            {{ t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import dayjs from "dayjs";
defineOptions({
  name: "Customer",
  inheritAttrs: false,
});

const { t } = useI18n();

import ProductAPI from "@/api/product";
import OrderAPI, { OrderPageVO, OrderQuery, OrderVO } from "@/api/order";
import UserAPI from "@/api/system/user";
import CustomerAPI from "@/api/customer";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);
const reNewFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const addOrder = ref(false);
const updateOrder = ref(false);
const showOrderStatus = ref(false);
const showOrderPaymentDialog = ref(false);
const showOrderPaymentResultDialog = ref(false);

const solutionOptions = reactive(new Map<number, { title: string }>([]));

const payResult = reactive<any>({
  PaymentType: "",
  PaymentDate: "",
  RtnCode: "",
  RtnMsg: "",
  TradeNo: "",
  TradeAmt: "",
  TradeDate: "",
});

const queryParams = reactive<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  status: 9,
});

const paymentData = reactive<any>({
  PaymentUrl: "",
  MerchantID: "",
  MerchantTradeNo: "",
  MerchantTradeDate: "",
  PaymentType: "",
  TotalAmount: 0,
  TradeDesc: "",
  ItemName: "",
  ReturnURL: "",
  ChoosePayment: "",
  ClientBackURL: "",
  OrderResultURL: "",
});

const list = ref<OrderPageVO[]>();

const productOptions = ref<OptionType[]>([]);

const renew_dialog = reactive({
  title: "",
  visible: false,
});

const payStatusOptions = ref<OptionType[]>([
  {
    label: t("common.all"),
    value: 9,
  },
  {
    label: t("order.payStatusOptions.0"),
    value: 0,
  },
  {
    label: t("order.payStatusOptions.1"),
    value: 1,
  },
]);

const renewRules = reactive({
  productId: [{ required: true, message: t("order.choose_product"), trigger: "blur" }],
  payMethod: [
    { required: true, message: t("common.choose") + t("order.payMethod"), trigger: "blur" },
  ],
});

function handleQuery() {
  loading.value = true;
  OrderAPI.getList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// reset query
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// select checkbox
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.deviceId);
}

const renewForm = reactive<OrderVO>({
  id: 0,
  status: 0,
  payMethod: "bank_transfer",
  productId: undefined,
  customerId: 0,
});

function handleRenewOpenDialog(customerId?: number) {
  renew_dialog.visible = true;
  addOrder.value = true;
  renewForm.customerId = customerId ?? 0;
  renewForm.status = 0;
  renew_dialog.title = t("order.renew");
  loading.value = true;
  ProductAPI.getListBySolutionId(renewForm.customerId)
    .then((res) => {
      if (res.total > 0) {
        const items: Array<any> = [];
        for (const item of res.list) {
          items.push({
            label: item.title + " - " + t("order.currencySmy") + " " + item.price + "",
            value: item.id,
          });
        }
        productOptions.value = items;
        console.log(productOptions.value);
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleRenewEditOpenDialog(id: number) {
  loading.value = true;
  OrderAPI.getFormData(id).then((res) => {
    renewForm.customerId = res.customerId;
    renewForm.id = res.id;
    renewForm.productId = res.productId;
    renewForm.payMethod = res.payMethod;

    updateOrder.value = true;
    renew_dialog.visible = true;
    renew_dialog.title = t("order.renew");

    CustomerAPI.getFormData(res.customerId).then((resCustomer) => {
      ProductAPI.getList({ solutionId: resCustomer.solutionId, pageNum: 1, pageSize: 10000 })
        .then((resP) => {
          if (resP.total > 0) {
            const items: Array<any> = [];
            for (const item of resP.list) {
              items.push({
                label: item.title + " - " + t("order.currencySmy") + " " + item.price + "",
                value: Number(item.id),
              });
            }
            productOptions.value = items;
            console.log(productOptions.value);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  });
}

// delete
function handleDelete(id: number) {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      OrderAPI.deleteByIds(id)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

function handleRenewSubmit() {
  reNewFormRef.value.validate((valid: any) => {
    if (valid) {
      OrderAPI.add(renewForm).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.message);
          handleRenewCloseDialog();
          handleResetQuery();
        } else {
          ElMessage.error(res.data.message);
        }
      });
    }
  });
}

function handleRenewEditSubmit() {
  reNewFormRef.value.validate((valid: any) => {
    if (valid) {
      OrderAPI.update(renewForm).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.message);
          handleRenewCloseDialog();
          handleResetQuery();
        } else {
          ElMessage.error(res.data.message);
        }
      });
    }
  });
}

// close dialog
function handleRenewCloseDialog() {
  renew_dialog.visible = false;
  addOrder.value = false;
  updateOrder.value = false;
  reNewFormRef.value.resetFields();
  reNewFormRef.value.clearValidate();
}

function gotoPay(orderId: number) {
  OrderAPI.getOrderPaymentInfo(orderId).then((res) => {
    Object.assign(paymentData, res);
    setTimeout(() => {
      document.getElementById("gotoPay")?.click();
      showOrderPaymentDialog.value = true;
    }, 1000);

    const clrT = setInterval(() => {
      OrderAPI.getFormData(orderId).then((res) => {
        if (res.status !== 0) {
          showOrderPaymentDialog.value = false;
          clearInterval(clrT);
          location.reload();
        }
      });
    }, 5000);
  });
}

function getProfile() {
  UserAPI.getProfile().then((res) => {
    if (res.userCustomerId === 0) {
      showOrderStatus.value = true;
    } else {
      showOrderStatus.value = false;
    }
  });
}

function showPayResult(result: string) {
  const res = JSON.parse(result);
  Object.assign(payResult, res);
  showOrderPaymentResultDialog.value = true;
}

import SolutionAPI from "@/api/solution/index";
function getSolutionOptions() {
  SolutionAPI.getList({ pageNum: 1, pageSize: 1000 })
    .then((data) => {
      data.list.forEach((item: any) => {
        solutionOptions.set(item.id, item.title);
      });
    })
    .finally(() => {});
}

onMounted(() => {
  getSolutionOptions();
  getProfile();
  handleQuery();
});
</script>
